/**
 * @author denis.onishchenko@gmail.com
 */

package com.prapp.mediag;

import java.io.IOException;
import java.io.InputStream;

import android.app.ActivityGroup;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabWidget;

public final class MainActivity extends ActivityGroup {

    private PRApplication application;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        application = (PRApplication) getApplication();

        TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
        tabHost.setup(getLocalActivityManager());

        int tabCount = application.getTabCount();

        for (int index = 0; index < tabCount; index++)
            try {
                addTab(index, tabHost);
            }
            catch (Throwable x) {
                Log.e(getClass().getName() + ".onCreate", "Can't create tab " + index, x);
            }
    }

    private void addTab(int index, TabHost tabHost) {
        Config.Tab tab = application.getTab(index);

        String name = tab.getName();
        if (name == null) name = "";

        String iconId = tab.getIcon();

        Class<?> activityClass = application.getActivityClass(index);

        String tag = "tab_" + index;

        Intent intent = new Intent();
        intent.setClass(this, activityClass);
        intent.putExtra(PRApplication.TAB_INDEX, index);

        TabHost.TabSpec tabSpec = tabHost.newTabSpec(tag);
        tabSpec.setIndicator(name);
        tabSpec.setContent(intent);

        tabHost.addTab(tabSpec);

        if (iconId != null) {
            try {
                TabWidget tabWidget = tabHost.getTabWidget();
                View childAt = tabWidget.getChildAt(index);
                ImageView view = (ImageView) childAt.findViewById(android.R.id.icon);
                Bitmap bitmap = createBitmap(iconId);
                view.setImageBitmap(bitmap);
            }
            catch (Throwable x) {
                Log.e(getClass().getName() + ".addTab", "Can't get bitmap " + iconId, x);
            }
        }
    }

    private Bitmap createBitmap(String path) throws IOException {
        InputStream is = getAssets().open(path.replace("@images/", ""), AssetManager.ACCESS_STREAMING);
        try {
            return BitmapFactory.decodeStream(is);
        }
        finally {
            is.close();
        }
    }
}
